import { login, getUserInfo, getUserInfoByid } from '@/api/user'
import { resetRouter } from '@/router/index'
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    localStorage.setItem('token', data)
    localStorage.setItem('loginTime', Date.now())
    state.token = data
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
    console.log(state.userInfo)
  },
  removeToken(state) {
    state.token = ''
    localStorage.removeItem('token')
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}
const actions = {
  async login(store, data) {
    const res = await login(data)
    store.commit('setToken', res)
  },
  async getUserInfo(store) {
    const res = await getUserInfo()
    const detail = await getUserInfoByid(res.userId)
    store.commit('setUserInfo', { ...res, ...detail })
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
    // 重置路由
    resetRouter()
    // 还有一步  vuex中的数据是不是还在
    // 要清空permission模块下的state数据
    // vuex中 user子模块  permission子模块
    // 子模块调用子模块的action  默认情况下 子模块的context是子模块的
    // 父模块 调用 子模块的action
    store.commit('permission/setRoutes', [], { root: true })
    // 子模块调用子模块的action 可以 将 commit的第三个参数 设置成  { root: true } 就表示当前的context不是子模块了 而是父模块
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

